package com.aaa.emp.config;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * fileName:MyRandomRule
 * description:
 * author:zz
 * createTime:2020/7/22 11:40
 * version:1.0.0
 */
public class MyRandomRule  extends AbstractLoadBalancerRule {
    public MyRandomRule() {
    }

    /**
     * 选择节点
     * @param lb
     * @param key
     * @return
     */
    @SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;
            System.out.println("lb开始："+lb);
            System.out.println("lb结束-----------");
            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }
                //获取在线的服务提供者列表
                List<Server> upList = lb.getReachableServers();
                System.out.println("获取在线的服务提供者列表："+upList);
                //获取所有服务提供者列表
                List<Server> allList = lb.getAllServers();
                System.out.println("------------------------------");
                System.out.println("获取所有服务提供者列表："+upList);
                //获取所有服务提供者的数量
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
                System.out.println("------------------------------");
                // 3
                System.out.println("当前服务提供者数量："+serverCount);
                int index = this.chooseRandomInt(serverCount);
                //upList.get(2)
                server = (Server)upList.get(index);
                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        //random.nextInt(3);  =  0 1  2
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
